const ejs = require('ejs')
const _ = require("lodash")
const fs = require("fs")
const path = require("path")
const mkdirp = require('mkdirp')
const phantom = require('phantom');

function getAbsPath(pathStr){
  return path.join(__dirname, pathStr)
}

const distPath = getAbsPath('../dist');
const htmlDistPath =  path.join(distPath, 'html')
mkdirp(distPath)
mkdirp(htmlDistPath)

const layoutHtmlStr = fs.readFileSync(getAbsPath(`../layout/echarts.ejs`), 'utf-8')
const wordcloudLayoutHtmlstr = fs.readFileSync(getAbsPath(`../layout/wordcloud.ejs`), 'utf-8')

const htmlStrMap = {
  wordcloud: wordcloudLayoutHtmlstr,
  china: layoutHtmlStr,
  line: layoutHtmlStr,
  bar: layoutHtmlStr, 
  pie: layoutHtmlStr
}

function fixPhantomPath(path) {
  var isWin = /^win/.test(process.platform);
  if (isWin) {
      path = path.slice(2).replace(/\\/g, '/');
  }
  return path;
}

function renderCharts(req, res, next){
  var chartConfig = req.body.chartConfig;
  var chartWidth = Number(req.body.width);
  var chartHeight = Number(req.body.height);
  var version = Number(req.body.version)
  var type = req.body.type
  if(!_.isObject(chartConfig)){
    return next('`chartConfig` should be an object')
  }
  if(!_.isNumber(chartWidth)){
    return next('`chartWidth` should be a positive number')
  }
  if(!_.isNumber(chartHeight)){
    return next('`chartHeight` should be a positive number')
  }
  if(!_.isNumber(version)){
    return next('`version` should be a positive number')
  }

  chartWidth = chartWidth || 800;
  chartHeight = chartHeight || 400;
  const clipRect = { top: 0, left: 0, width: chartWidth, height: chartHeight };
  version = version || 5;
  let chartHtmlPath = path.join(htmlDistPath,`0.html`);
  let chartHtmlStr = ejs.render(htmlStrMap[type], {chartConfigStr:JSON.stringify(chartConfig), chartWidth, chartHeight, version})
  fs.writeFile(chartHtmlPath, chartHtmlStr, (err)=>{
    if(err){
      return next(err)
    }
    var urlPath = fixPhantomPath(chartHtmlPath);
    htmlToBase64Img(urlPath, clipRect).then((pngBase64) => {
      res.send("data:image/jpeg;base64," + pngBase64)
      //fs.unlink(chartHtmlPath, ()=>{});
    })
  })

}


function htmlToBase64Img(url, clipRect) {
  var sitepage = void 0;
  var phInstance = void 0;
  return phantom.create().then(function (instance) {
      phInstance = instance;
      return instance.createPage();
  }).then(function (page) {
      sitepage = page;
      return page.open(`http://localhost:3000/0.html`);
  }).then(function (status) {
      return sitepage.property('content');
  }).then(()=>{
      return sitepage.renderBase64(('PNG'))
  }).then((canvas)=>{
    sitepage.close();
    phInstance.exit();
    return canvas
  })
  .catch(function (error) {
      sitepage.close();
      phInstance.exit();
      throw new Error(error)
  });
}


module.exports = renderCharts